import time
import requests
from fl.config import Config
from fl.util.chain import BlockchainManager
from fl.logger import logger

def send_heartbeat(config: Config, chain: BlockchainManager):
    try:
        requests.post(f'{config.DETECTOR_PROTOCOL}://{config.DETECTOR_HOST}:{config.DETECTOR_PORT}'
                      f'/heartbeat', json={'node_address': chain.account})
        # print("Heartbeat sent")
    except Exception as e:
        logger.error(f"Failed to send heartbeat: {e}")


def start_heartbeat(config: Config, chain: BlockchainManager):
    while True:
        send_heartbeat(config, chain)
        time.sleep(1)  # 每秒发送一次心跳信号
